/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2015 Umeng, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.umeng.commm.ui.activities;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.umeng.comm.core.beans.CommConfig;
import com.umeng.comm.core.beans.Topic;
import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.constants.ErrorCode;
import com.umeng.comm.core.listeners.Listeners;
import com.umeng.comm.core.listeners.Listeners.OnResultListener;
import com.umeng.comm.core.listeners.Listeners.SimpleFetchListener;
import com.umeng.comm.core.nets.responses.LoginResponse;
import com.umeng.comm.core.utils.BitmapUtils;
import com.umeng.comm.core.utils.CommonUtils;
import com.umeng.comm.core.utils.ResFinder;
import com.umeng.comm.core.utils.ResFinder.ResType;
import com.umeng.commm.ui.anim.CustomAnimator;
import com.umeng.commm.ui.fragments.HotTopicFeedFragment;
import com.umeng.commm.ui.fragments.LastestTopicFeedFragment;
import com.umeng.commm.ui.fragments.RecommendTopicFeedFragment;
import com.umeng.commm.ui.fragments.TopicFeedFragment;
import com.umeng.commm.ui.mvpview.MvpTopicDetailView;
import com.umeng.commm.ui.presenter.impl.TopicDetailPresenter;
import com.umeng.commm.ui.widgets.TopicIndicator;

/**
 * 话题详情页
 */
public class TopicDetailActivity extends BaseFragmentActivity implements OnClickListener,
        MvpTopicDetailView {

    /**
     * 话题详情的Fragment
     */
    private TopicFeedFragment mDetailFragment;
    private LastestTopicFeedFragment lastestTopicFeedFragment;
    private RecommendTopicFeedFragment recommendTopicFeedFragment;
    private HotTopicFeedFragment hotTopicFeedFragment;
//    private ActiveUserFragment mActiveUserFragment;
    private Topic mTopic;
    private TopicIndicator mIndicator;
    private ViewPager mViewPager;
    private String[] mTitles = null;
    private FragmentPagerAdapter mAdapter;
//    private ToggleButton mFollowToggleBtn;
    private TopicDetailPresenter mPresenter;
    private ImageButton postBtn;
    private ToggleButton favouriteBtn;
    public static int HOTTYPE = 0;
    private PopupWindow hotpop;
    private boolean isClick = true;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        mPresenter = new TopicDetailPresenter(this, this);
        setContentView(ResFinder.getLayout("umeng_commm_topic_detail_layout"));
        mTopic = getIntent().getExtras().getParcelable(Constants.TAG_TOPIC);
        if (mTopic == null) {
            finish();
            return;
        }
        mTitles = getResources().getStringArray(
                ResFinder.getResourceId(ResType.ARRAY, "umeng_commm_topic_detail_tabs"));
        // 根据话题的id信息初始化fragment
        initView();
        mPresenter.onCreate(arg0);
    }

    private void initView() {
        mIndicator = (TopicIndicator) findViewById(ResFinder.getId("indicator"));
        mViewPager = (ViewPager) findViewById(ResFinder.getId("viewPager"));
        mIndicator.setTabItemTitles(mTitles);
        mIndicator.setVisibleTabCount(4);
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return 4;
            }

            @Override
            public Fragment getItem(int pos) {
                return getFragment(pos);
            }
        };
        mViewPager.setAdapter(mAdapter);
        // 设置关联的ViewPager
        mIndicator.setViewPager(mViewPager, 0);

        // 初始化Header的控件跟数据
//        initHeader();
        initTitle();
    }

    /**
     * 初始化标题栏相关控件跟设置数据</br>
     */
    private void initTitle() {
        findViewById(ResFinder.getId("umeng_comm_title_back_btn")).setOnClickListener(this);
        TextView titleTextView = (TextView) findViewById(ResFinder.getId("umeng_comm_title_tv"));
        titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        titleTextView.setTextColor(ResFinder.getColor("umeng_comm_title"));
        titleTextView.setText(mTopic.name);
        findViewById(ResFinder.getId("umeng_comm_title_setting_btn")).setVisibility(View.GONE);
        favouriteBtn = (ToggleButton) findViewById(ResFinder.getId("umeng_comm_favourite_btn"));
        favouriteBtn.setVisibility(View.VISIBLE);
        postBtn = (ImageButton) findViewById(ResFinder.getId("umeng_comm_post_btn"));
        postBtn.setVisibility(View.VISIBLE);
        setTopicStatus();
        mPresenter.SetFavouriteButton(favouriteBtn);
        favouriteBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                favouriteBtn.setClickable(false);


                CommonUtils.checkLoginAndFireCallback(TopicDetailActivity.this,
                        new SimpleFetchListener<LoginResponse>() {

                            @Override
                            public void onComplete(LoginResponse response) {
                                favouriteBtn.setChecked(!favouriteBtn.isChecked());
                                if (response.errCode != ErrorCode.NO_ERROR) {
                                    favouriteBtn.setChecked(!favouriteBtn.isChecked());
                                    return;
                                }
                                if (favouriteBtn.isChecked()) {
                                    mPresenter.cancelFollowTopic(mTopic);
                                } else {
                                    mPresenter.followTopic(mTopic);
                                }
                                isClick = true;

//                                    favouriteBtn.setClickable(true);
                            }
                        });

            }
        });
        postBtn.setOnClickListener(new Listeners.LoginOnViewClickListener() {
            @Override
            protected void doAfterLogin(View v) {
                gotoPostFeedActivity();
            }
        });
        favouriteBtn.setTextOff("");
        favouriteBtn.setTextOn("");
        initPopWindow();
        mIndicator.SetIndictorClick(new IndicatorListerner());
    }

    private class IndicatorListerner implements TopicIndicator.IndicatorListener {
        @Override
        public void SetItemClick() {
            int cCount = mIndicator.getChildCount();
            for (int i = 0; i < cCount; i++) {
                final int j = i;
                View view = mIndicator.getChildAt(i);
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (j == 3) {
                            if (hotpop.isShowing()) {
                                hotpop.dismiss();
                            } else {
                                hotpop.showAsDropDown(v,CommonUtils.dip2px(TopicDetailActivity.this,-50),15);
                            }
                        }
                        else {
                            mViewPager.setCurrentItem(j);
                        }
                    }
                });
            }
        }
    }
    private void initPopWindow(){
        final LinearLayout topicGroup = new LinearLayout(this);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN){
            topicGroup.setBackground(ResFinder.getDrawable("xialakuang_right"));
        }else{
            topicGroup.setBackgroundDrawable(ResFinder.getDrawable("xialakuang_right"));
        }
        topicGroup.setOrientation(LinearLayout.VERTICAL);
        String[] titles =  getResources().getStringArray(
                ResFinder.getResourceId(ResType.ARRAY, "umeng_commm_topic_feed_titles"));
        for (int i = 0; i < 4; i++) {
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,  LinearLayout.LayoutParams.WRAP_CONTENT);
            tv.setPadding(10, 10, 10, 10);
            tv.setGravity(Gravity.CENTER);
            tv.setText(titles[i]);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
            tv.setLayoutParams(lp);
            tv.setBackgroundColor(Color.TRANSPARENT);
            tv.setTextColor(ResFinder.getColor("umeng_text_common_default"));
            final int j = i;
            tv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    ((TextView) topicGroup.getChildAt(HOTTYPE)).setTextColor(ResFinder.getColor("umeng_text_common_default"));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        ((TextView) topicGroup.getChildAt(HOTTYPE)).setBackground(null);
                    } else {
                        ((TextView) topicGroup.getChildAt(HOTTYPE)).setBackgroundDrawable(null);
                    }
                    boolean isneed = false;
                    if (HOTTYPE!=j)
                    {
                        isneed = true;
                    }
                    HOTTYPE = j;
                    ((HotTopicFeedFragment) (mAdapter.getItem(3))).ChangeFragment(HOTTYPE,isneed);
                    mViewPager.setCurrentItem(3);
                    ((TextView) view).setTextColor(ResFinder.getColor("umeng_text_common_selected"));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        ((TextView) topicGroup.getChildAt(HOTTYPE)).setBackground(ResFinder.getDrawable("umeng_hot_btn_shape_round"));
                    } else {
                        ((TextView) topicGroup.getChildAt(HOTTYPE)).setBackgroundDrawable(ResFinder.getDrawable("umeng_hot_btn_shape_round"));
                    }

                    if (hotpop != null && hotpop.isShowing()) {
                        hotpop.dismiss();
                    }
                }
            });
            if (i == 0){
                HOTTYPE = 0;
                tv.setTextColor(ResFinder.getColor("umeng_text_common_selected"));
                tv.setBackgroundResource(ResFinder.getResourceId(ResType.DRAWABLE, "umeng_hot_btn_shape_round"));
            }
            topicGroup.addView(tv);
        }
        hotpop = new PopupWindow(topicGroup, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        hotpop.setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0000000000);
        hotpop.setBackgroundDrawable(dw);
        hotpop.update();
    }
    /**
     * 跳转至发送新鲜事页面</br>
     */
    private void gotoPostFeedActivity() {
        Intent postIntent = new Intent(TopicDetailActivity.this, PostFeedActivity.class);
        postIntent.putExtra(Constants.TAG_TOPIC, mTopic);
        startActivity(postIntent);
    }
    /**
     * 获取对应的Fragment。0：话题聚合 1：活跃用户</br>
     * 
     * @param pos
     * @return
     */
    private Fragment getFragment(int pos) {
        if (pos == 0) {
            if (mDetailFragment == null) {
                mDetailFragment = TopicFeedFragment.newTopicFeedFrmg(mTopic);
            }
            mDetailFragment.setOnAnimationListener(mListener);
            return mDetailFragment;
        } else if (pos == 1) {
            if (lastestTopicFeedFragment == null) {
                lastestTopicFeedFragment = LastestTopicFeedFragment.newTopicFeedFrmg(mTopic);
            }
            lastestTopicFeedFragment.setOnAnimationListener(mListener);
            return lastestTopicFeedFragment;
        }else if (pos == 2) {
            if (recommendTopicFeedFragment == null) {
                recommendTopicFeedFragment = RecommendTopicFeedFragment.newTopicFeedFrmg(mTopic);
            }
            recommendTopicFeedFragment.setOnAnimationListener(mListener);
            return recommendTopicFeedFragment;
        }else if (pos == 3) {
            if (hotTopicFeedFragment == null) {
                hotTopicFeedFragment = HotTopicFeedFragment.newTopicFeedFrmg(mTopic);
            }
            hotTopicFeedFragment.setOnAnimationListener(mListener);
            return hotTopicFeedFragment;
        }
        return null;
    }

    private void initHeader() {
        // 话题描述
//        TextView topicDescTv = (TextView) findViewById(ResFinder.getId(
//                "umeng_comm_topic_desc_tv"));
//        String desc = mTopic.desc;
//        String noDescStr = ResFinder.getString("umeng_comm_topic_no_desc");
//        boolean hasText = TextUtils.isEmpty(desc) || "null".equals(desc);
//        String showText = hasText ? noDescStr : desc;
//        topicDescTv.setText(showText);
//
//        mFollowToggleBtn = (ToggleButton)
//                findViewById(ResFinder.getId("umeng_comm_topic_toggle_btn"));
//        mPresenter.checkIsFollowed(mTopic.id, new OnResultListener() {
//
//            @Override
//            public void onResult(int status) {
//                mFollowToggleBtn.setChecked(status == 1);
//            }
//        });
//
//        setTopicStatus();
//        mFollowToggleBtn.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                CommonUtils.checkLoginAndFireCallback(TopicDetailActivity.this,
//                        new SimpleFetchListener<LoginResponse>() {
//
//                            @Override
//                            public void onComplete(LoginResponse response) {
//                                mFollowToggleBtn.setChecked(!mFollowToggleBtn.isChecked());
//                                if (response.errCode != ErrorCode.NO_ERROR) {
//                                    mFollowToggleBtn.setChecked(!mFollowToggleBtn.isChecked());
//                                    return;
//                                }
//                                if (mFollowToggleBtn.isChecked()) {
//                                    mPresenter.cancelFollowTopic(mTopic);
//                                } else {
//                                    mPresenter.followTopic(mTopic);
//                                }
//                            }
//                        });
//            }
//        });
//
//        mHeaderView = (LinearLayout) findViewById(ResFinder.getId("umeng_comm_topic_header"));

    }

//    private LinearLayout mHeaderView = null;
    private CustomAnimator mCustomAnimator = new CustomAnimator();
    private OnResultListener mListener = new OnResultListener() {

        @Override
        public void onResult(int status) {
//            if (status == 1) {// dismiss
//                mCustomAnimator.startDismissAnimation(mHeaderView);
//            } else if (status == 0) { // show
//                mCustomAnimator.startShowAnimation(mHeaderView);
//            }
        }
    };
    
    /**
     * 检查当前登录用户是否已关注该话题，并设置ToggleButton的状态</br>
     */
    private void setTopicStatus() {
        String loginUserId = CommConfig.getConfig().loginedUser.id;
        if (TextUtils.isEmpty(loginUserId)) {
            Log.d("###", "### user dont login...");
            return;
        }
        com.umeng.comm.core.utils.Log.d("topic","is focused"+mTopic.isFocused);
        favouriteBtn.setChecked(mTopic.isFocused);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == ResFinder.getId("umeng_comm_title_back_btn")) {
            finish();
        }
    }

    @Override
    public void setToggleButtonStatus(boolean status) {
        favouriteBtn.setClickable(true);
        favouriteBtn.setChecked(status);
    }

}
